<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use app\common\constant\Common;
use app\common\service\Media;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\BotKeyword as KeywordM;
use plugin\wechat\app\service\BotReply as ReplyService;
use plugin\wechat\app\TenantController;
use plugin\wechat\app\service\BotTask as TaskService;
use Support\Request;
use plugin\wechat\app\service\BotKeyword as KeywordService;
use plugin\wechat\app\service\BotFriend as  FriendService;
use plugin\wechat\app\service\Bot as  BotService;

class Botkeyword extends TenantController
{
    /**
     * @var KeywordM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new KeywordM();
    }

    private function tabList(){
        $tab_list = [];
        $events = ReplyService::events();
        foreach ($events as $k => $v){
            $tab_list[$k] = [
                'title' => $events[$k],
                'href' => url('index', ['event' => $k])
            ];
        }
        return $tab_list;
    }


    public function index(){
        $bot = \request()->botInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['bot_id' ,'=', $bot['id']],
            ];
            !empty($post_data['search_key']) && $where[] = ['keyword', 'like', '%' . $post_data['search_key'] . '%'];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
                foreach ($list as $k => $v){
                    if($material = Media::getModel($v['media_type'])->where([
                        $this->tenantWhere(),
                        ['id' ,'=', $v['media_id']]
                    ])->find()){
                        $v['media_title'] = $v['media_type'] == 'text' ? $material['content'] : $material['title'];
                    }
                    $list[$k] = $v;
                }
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
                ['type' => 'text', 'name' => 'search_key', 'title' => '关键词']
            ])
            ->addTopButton('addnew')
            ->addTopButton('addnew', ['text' => '从其他机器人复制','title' => '从其他机器人复制', 'href' => url('copy'), 'class' => 'layui-btn layui-btn-sm'])
            ->addTopButton('forbid')
            ->addTableColumn(['title' => '', 'type' => 'checkbox'])
            ->addTableColumn(['title' => '关键词', 'field' => 'keyword', 'minWidth' => 100])
            ->addTableColumn(['title' => '回复类型', 'field' => 'media_type', 'minWidth' => 100])
            ->addTableColumn(['title' => '回复内容', 'field' => 'media_title', 'minWidth' => 100])
            ->addTableColumn(['title' => '批量指定', 'field' => 'user_type', 'type' => 'enum','options' => TaskService::userTypes(),'minWidth' => 100])
            ->addTableColumn(['title' => '自由指定', 'field' => 'wxids', 'minWidth' => 100])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'switch', 'options' => Common::status()])
            ->addTableColumn(['title' => '创建时间', 'field' => 'create_time',  'minWidth' => 170])
            ->addTableColumn(['title' => '修改时间', 'field' => 'update_time', 'minWidth' => 170])
            ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete');
        return $builder->show();
    }

    /**
     * 快速复制
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function copy()
    {
        $bot = \request()->botInfo;
        if(request()->isPost()){
            $post_data = input('post.');
            $exists = $this->model->where([
                $this->tenantWhere(),
                ['bot_id' ,'=', $bot['id']]
                ])->column('keyword');

            $list = $this->model->where([
                $this->tenantWhere(),
                ['bot_id' ,'=', $post_data['bot_id']],
                ['status','=', 1],
                ['keyword' ,'notin', count($exists) ? $exists : [0]]
            ])->select();
            foreach ($list as $v){
                unset($v['id']);
                $v['bot_id'] = $bot['id'];
                $v['wxids'] = '';
                $this->model->createOne($v);
            }
            return $this->success('操作成功！', '');
        }
        $bot_list = BotService::getIdToTitle(null, [['id', '<>', $bot['id']]]);
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('复制内容')
            ->setPostUrl(url('copy'))
            ->addFormItem('bot_id', 'chosen', '机器人', '请选择', $bot_list, 'required');

        return $builder->show();
    }

    public function add()
    {
        $material = [];
        $members = FriendService::getWxidToNickname();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增')
            ->setPostUrl(url('savePost'))
            ->addFormItem('keyword', 'text', '关键词', '30字内', [], 'required maxlength=30')
            ->addFormItem('media', 'choose_media', '选择素材', '选择素材', ['types' => Media::types()], 'required')
            ->addFormItem('need_at', 'radio', '艾特提问者', '在群聊中是否艾特提问者', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('user_type', 'radio', '批量选择', '批量选择', TaskService::userTypes())
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '此处若填写，会覆盖批量选择的值', $members)
            ->setFormData(['need_at' => 0]);

        return $builder->show(['material' => $material]);
    }

    public function edit()
    {
        $bot = \request()->botInfo;
        $id = input('id', null);
        $data = $this->model->where([
            $this->tenantWhere(),
            ['bot_id','=',$bot['id']]
        ])->find($id);

        if (!$data) {
            return $this->error('参数错误!');
        }
        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);
        $material = Media::getModel($data['media_type'])->where([
            $this->tenantWhere(),
            ['id' ,'=', $data['media_id']]
        ])->find();

        $members = FriendService::getWxidToNickname();
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('编辑')
            ->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('keyword', 'text', '关键词', '30字内', [], 'required maxlength=30')
            ->addFormItem('media', 'choose_media', '选择素材', '选择素材', ['types' => Media::types(), 'id' => $data['media_id'], 'type' => $data['media_type']], 'required')
            ->addFormItem('need_at', 'radio', '艾特提问者', '在群聊中是否艾特提问者', [0 => '否', 1 => '是'], 'required')
            ->addFormItem('sort', 'number', '排序', '数字越大优先级越高', [], 'required min=0')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'])
            ->addFormItem('zddx_legend', 'legend', '指定对象', '指定对象')
            ->addFormItem('user_type', 'radio', '批量选择', '批量选择', TaskService::userTypes())
            ->addFormItem('wxids', 'chosen_multi', '自由选择', '此处若填写，会覆盖批量选择的值', $members)
            ->setFormData($data);

        return $builder->show(['material' => $material]);
    }

    public function savePost(Request $request, $jump_to = '', $data = [])
    {
        $bot = $request->botInfo;
        $post_data = input('post.');
        $post_data['company_id'] = TenantService::getCompanyId();
        $post_data['bot_id'] = $bot['id'];
        if(empty($post_data[$this->pk])){
            $res = $this->model->createOne($post_data);
        }else {
            $res = $this->model->update($post_data);
        }
        if($res){
            KeywordService::getKeywordsByBot([
                'bot_id' => $bot['id'],
                'keyword' => $post_data['keyword'],
                'refresh' => true
            ]);
            return $this->success('操作成功!', $jump_to);
        }else{
            return $this->error('操作失败!', '', ['token' => token()]);
        }
    }
}